package com.huayun.plugin.bdfAnalysis.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huayun.plugin.fastener.service.FileParser;
import com.huayun.plugin.fastener.vo.FiberMaterial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("bdfAnalysis")
public class BDFAnalysisController {
    @Autowired
    private FileParser fileParser;

    // 新增接口：上传并解析BDF文件
    @PostMapping("/uploadBdf")
    public ResponseEntity<String> uploadBdfFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Please select a file to upload.");
        }
        try {
            Map<String, List<Map<String, Object>>> parsedLines = fileParser.parseBDFFile(file);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResult = objectMapper.writeValueAsString(parsedLines);
            System.out.println(jsonResult);
            // 这里可以添加对解析后数据的处理逻辑
            return ResponseEntity.ok(jsonResult);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to parse BDF file: " + e.getMessage());
        }
    }
    @PostMapping("/exportBdfToExcel")
    public ResponseEntity<InputStreamResource> exportBdfToExcel(@RequestBody Map<String, List<Map<String, Object>>> parsedData) throws IOException {

        // 导出 cquad4Lines 到 Excel 文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        fileParser.exportBdfToExcel(parsedData, outputStream);

        // 准备响应
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=bdf_output.xlsx");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(new InputStreamResource(inputStream));
    }

    @PostMapping("/uploadBdfExcel")
    public  ResponseEntity<String> uploadBdfExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Please select a file to upload.");
        }

        try {
            InputStream inputStream = file.getInputStream();
            List<Map<String, Object>> CQUAD = fileParser.parseBdfExcelFile(inputStream);
            inputStream.close();

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResult = objectMapper.writeValueAsString(CQUAD);
            System.out.println(jsonResult);
            return ResponseEntity.ok(jsonResult);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Please select a file to upload.");
        }
    }

    @PostMapping("/uploadFibersimExcel")
    public  ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Please select a file to upload.");
        }

        try {
            InputStream inputStream = file.getInputStream();
            List<FiberMaterial> materials = fileParser.parseExcelFile(inputStream);
            inputStream.close();

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResult = objectMapper.writeValueAsString(materials);
            System.out.println(jsonResult);
            return ResponseEntity.ok(jsonResult);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Please select a file to upload.");
        }
    }
    @PostMapping("/comparisonResult")
    public ResponseEntity<InputStreamResource> comparisonResult(@RequestBody List<Map<String, String>> parsedData) throws IOException{
        // 导出 cquad4Lines 到 Excel 文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        fileParser.exportExcel(parsedData, outputStream);

        // 准备响应
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=bdf_output.xlsx");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(new InputStreamResource(inputStream));
    }

    @Autowired
    private BDFAnalysisService  bdfAnalysisService;
    public BDFAnalysisController(BDFAnalysisService bdfAnalysisService) {
        this.bdfAnalysisService = bdfAnalysisService;
    }



    @PostMapping("/getIntersectFaces")
    public ResponseEntity<List<List<Integer>>> getIntersectFaces(@RequestBody BDFAnalysisService.IntersectFacesParam param){
        List<List<Integer>> listlistID = bdfAnalysisService.calculateIntersectFaces(param.getLinesInfo(),param.getFacesInfo());

        return ResponseEntity.ok(listlistID);
    }
}
